﻿using System;
using System.Diagnostics;
using System.IO;

namespace Personal.BuildAsSilverlight4
{
    public static class ExceptionHandler
    {
        public static void WriteToLog(Exception exception)
        {
            try
            {
                var logFile = GetLogFile();
                logFile.WriteLine(BuildLogMessage(exception));
                logFile.Flush();
                logFile.Close();
            }
            catch
            {
                WriteToSystemLog(exception);
            }

        }

        #region Private Methods
        private static StreamWriter GetLogFile()
        {
            if (!File.Exists(Constants.ADDIN_NAME))
                File.CreateText(Constants.ADDIN_NAME);
            return File.AppendText(Constants.ADDIN_NAME);
        }

        private static void WriteToSystemLog(Exception exception)
        {
            EventLog.WriteEntry(Constants.ADDIN_NAME, BuildLogMessage(exception), EventLogEntryType.Error);
        }

        private static string BuildLogMessage(Exception exception)
        {
            return DateTime.Now + "#" + exception.Message + "#" + exception.StackTrace;
        }
        #endregion
    }
}
